package com.tsmti.lab.controller.preprocessing;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.tsmti.core.common.annotation.SameUrlData;
import com.tsmti.core.common.controller.BaseCrudController;
import com.tsmti.core.common.model.AjaxJson;
import com.tsmti.core.common.query.data.Page;
import com.tsmti.core.common.query.data.PageImpl;
import com.tsmti.core.common.query.data.PageJson;
import com.tsmti.core.common.query.data.PropertyPreFilterable;
import com.tsmti.core.common.query.data.Queryable;
import com.tsmti.core.util.ConvertUtil;
import com.tsmti.core.util.DateUtils;
import com.tsmti.core.util.StringUtils;
import com.tsmti.doctor.dto.RequisitionView;
import com.tsmti.doctor.entity.PimsPathologyRequisition;
import com.tsmti.doctor.entity.PimsReqFieldNurse;
import com.tsmti.doctor.entity.PimsReqMaterialNurse;
import com.tsmti.doctor.service.PimsPathologyRequisitionService;
import com.tsmti.doctor.service.PimsReqFieldNurseService;
import com.tsmti.doctor.service.PimsReqMaterialNurseService;
import com.tsmti.lab.util.DoctorUtils;
import com.tsmti.shiro.annotation.RequiresPathPermission;
import com.tsmti.util.UserUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.tsmti.core.common.constant.Constants.THREE;

/**
 * @Package：com.tsmti.lab.controller.preprocessing
 * @Class：inReceive
 * @Description： TODO
 * @Author：dcd
 * @Date：Created in 2018/11/13 10:33 AM
 * @Company:
 * @Version：
 * @Modified By:
 */
@RequestMapping("/preProcessing/inReceive")
@Controller
@RequiresPathPermission("preProcessing:inReceive")
public class InReceiveController extends BaseCrudController<PimsPathologyRequisition, Long> {
    @Autowired
    private PimsPathologyRequisitionService requisitionService;
    @Autowired
    private PimsReqMaterialNurseService materialNurseService;
    @Autowired
    private PimsReqFieldNurseService fieldNurseService;

    @Override
    public void preAjaxList(Queryable queryable, DetachedCriteria detachedCriteria, HttpServletRequest request,
                            HttpServletResponse response) {
        String reqState = ConvertUtil.null2String(request.getParameter("reqState"));
        String reqPatientName = ConvertUtil.null2String(request.getParameter("reqPatientName"));
        String requisitionNo = ConvertUtil.null2String(request.getParameter("requisitionNo"));
        String reqDate = ConvertUtil.null2String(request.getParameter("reqDate"));
        queryable.addCondition("reqState||eq", reqState);
        queryable.addCondition("reqPatientName||eq", reqPatientName);
        queryable.addCondition("requisitionNo||eq", requisitionNo);
        queryable.addCondition("reqDate||between", reqDate);
        queryable.addCondition("delFlag||eq", "0");
        String orgId = UserUtils.getOrgId();
        if (StringUtils.isNotEmpty(orgId)) {
            queryable.addCondition("orgId||eq", orgId);
        }
    }


    @Override
    public void preList(Model model, HttpServletRequest request, HttpServletResponse response) {
        Map<String, String> queryValue = new HashMap<>(2);
        queryValue.put("startTime", ConvertUtil.getFormatDate(DateUtils.getExpDay(new Date(), -1), "yyyy-MM-dd") + " 00:00");
        queryValue.put("endTime", ConvertUtil.getFormatDate(new Date(), "yyyy-MM-dd") + " 23:59");
        model.addAttribute("queryValue", queryValue);
    }

    @RequestMapping(value = "getList", method = {RequestMethod.GET, RequestMethod.POST})
    public void getList(@ModelAttribute RequisitionView model, Queryable queryable, PropertyPreFilterable propertyPreFilterable, HttpServletRequest request,
                        HttpServletResponse response) throws IOException {
        model.setOrgId(UserUtils.getOrgId());
        int total = requisitionService.getInReceiveListCount(model);
        Page<RequisitionView> list = requisitionService.getInReceiveList(model, queryable, total);
        PageJson<RequisitionView> pageJson = new PageJson<>(list);
        SerializeFilter filter = propertyPreFilterable.constructFilter(entityClass);
        String content = JSON.toJSONString(pageJson, filter);
        StringUtils.printJson(response, content);
    }


    @RequestMapping(value = "getName", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public AjaxJson getName(HttpServletRequest request, HttpServletResponse response) {
        String code = ConvertUtil.null2String(request.getParameter("code"));
        String name = DoctorUtils.getNameByCode(code);
        AjaxJson ajaxJson = AjaxJson.success();
        if (StringUtils.isNotEmpty(name)) {
            ajaxJson.put("name", name);
        } else {
            ajaxJson = AjaxJson.fail("未找到该工号");
        }
        return ajaxJson;
    }

    @SameUrlData
    @RequestMapping(value = "receive", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public AjaxJson receive(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson ajaxJson = AjaxJson.success("接收成功");
        String requisitionNo = ConvertUtil.null2String(request.getParameter("requisitionNo"));
        String reqReceiveUser = ConvertUtil.null2String(request.getParameter("reqReceiveUser"));
        PimsPathologyRequisition pimsPathologyRequisition = requisitionService.getByRequisitionNo(requisitionNo, UserUtils.getOrgId());
        pimsPathologyRequisition.setReqReceiveUser(reqReceiveUser);
        pimsPathologyRequisition.setReqReceiveTime(new Date());
        pimsPathologyRequisition.setReqState(3L);
        requisitionService.save(pimsPathologyRequisition);
        return ajaxJson;
    }

    @RequestMapping(value = "getRequisition", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public AjaxJson getRequisition(HttpServletRequest request, HttpServletResponse response) {
        String requisitionNo = ConvertUtil.null2String(request.getParameter("requisitionNo"));
        PimsPathologyRequisition requisition = requisitionService.getByRequisitionNo(requisitionNo, UserUtils.getOrgId());
        AjaxJson ajaxJson = AjaxJson.success();
        if (requisition != null) {
            if (requisition.getReqState() >= THREE) {
                ajaxJson = AjaxJson.fail("该申请单已接收");
                return ajaxJson;
            }
            if (requisition.getReqState() == -1) {
                ajaxJson = AjaxJson.fail("该申请单已撤销，无法接收");
                return ajaxJson;
            }
            if (requisition.getReqState() == 0) {
                ajaxJson = AjaxJson.fail("未找到该申请");
                AjaxJson.fail("该申请单未执行医嘱，无法接收s");
                return ajaxJson;
            }
            ajaxJson.put("id", requisition.getId());
        } else {
            ajaxJson = AjaxJson.fail("未找到该申请");
        }
        return ajaxJson;
    }

    @Override
    public void preEdit(PimsPathologyRequisition entity, Model model, HttpServletRequest request, HttpServletResponse response) {
        List<PimsReqFieldNurse> fieldNurseList = fieldNurseService.getByRequisitionId(entity.getId());
        List<PimsReqFieldNurse> list = new ArrayList<>();
        //只取值为1的显示
        for (PimsReqFieldNurse fieldNurse : fieldNurseList) {
            if ("1".equals(fieldNurse.getReqfValue())) {
                list.add(fieldNurse);
            }
        }
        model.addAttribute("id", entity.getId());
        model.addAttribute("pathologyId", entity.getPathologyId());
        model.addAttribute("fieldNurseList", list);
    }

    @RequestMapping(value = "getDetailsList", method = {RequestMethod.GET, RequestMethod.POST})
    public void getDetailsList(Queryable queryable, PropertyPreFilterable propertyPreFilterable, HttpServletRequest request, HttpServletResponse response) {
        Long id = ConvertUtil.getLongValue(request.getParameter("id"));
        SerializeFilter filter = propertyPreFilterable.constructFilter(entityClass);
        List<PimsReqMaterialNurse> materialNurseList = materialNurseService.getByRequisitionId(id);
        Page<PimsReqMaterialNurse> materialNursePage = new PageImpl<PimsReqMaterialNurse>(materialNurseList, queryable.getPageable(), materialNurseList.size());
        PageJson<PimsReqMaterialNurse> pageJson = new PageJson<>(materialNursePage);
        String content = JSON.toJSONString(pageJson, filter);
        StringUtils.printJson(response, content);
    }
}
